#!/bin/bash
# Copyright (c) 2013, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.
# created on 2013-01-20

main() {
NAME="v6-afraid.sh"
PIDF="/var/run/$NAME.pid"
BIN="/usr/local/bin/$NAME"
LOG="/var/log/$NAME.log"
case "$1" in
    start)
	if [ -f "$PIDF" ]; then
		PID=$(cat ${PIDF})
		kill -0 ${PID} &>/dev/null
		if [ $? = 0 ]; then
			echo "$NAME already running."
		else
			start
		fi
	else
	    start
        fi
        ;;
    stop)
	stop
        ;;
    reload|restart)
        stop
        start
        ;;
    *)
        echo "Usage: $0 start|stop|restart|reload"
        exit 1
esac
exit 0
}

start() {
			$BIN > $LOG 2>&1 &
			echo $! > $PIDF
			PID=$(cat ${PIDF})
			sleep 0.2
			kill -0 ${PID} &>/dev/null
			if [ $? = 0 ]; then
				echo "$NAME started succesfully."
			else
				echo "Error starting $NAME"
			fi
}

stop() {
	if [ -f $PIDF ];then
		PID=$(cat ${PIDF})
		kill -0 ${PID} &>/dev/null
		if [ $? = 0 ]; then
			kill ${PID}
			sleep 0.5
			kill -0 ${PID} &>/dev/null
			if [ $? = 1 ]; then
				echo "$NAME stopped succesfully."
			else
				echo "Error stopping $NAME"
			fi
		else
			echo "$NAME is already stopped."
			rm -v $PIDF
		fi
	else
		echo "$NAME is already stopped."
	fi
}

main "$@"
